<?php
namespace databaseFunctions;
require_once 'model/Database.php';

class DatabaseFunctions{
	private $db;
	
	public function __construct(){
		$this->db = new \database\Database();
		$this->con = $this->db->getDatabase();
	}
	//returns alla comments to ViewPost
	public function getDbResults(){
		$result = mysqli_query($this->con,"SELECT * FROM comments");
		
		return $result;
	}
	//adds user to database
	public function addUser($user, $password){
			$sql = "INSERT INTO users (Username, Password)
			VALUES (?,?)";
			$stmt = mysqli_prepare($this->con, $sql);
			mysqli_stmt_bind_param ($stmt, "ss",$user, $password);
			mysqli_stmt_execute($stmt);
			mysqli_stmt_close($stmt);
			mysqli_close($this->con);
	}
	
	public function existingUsername(){
		$result = mysqli_query($this->con,"SELECT Username FROM users");

		while($row = mysqli_fetch_array($result)){
			if($username == $row['Username']){
				return TRUE;
			}
			return FALSE;
  		}
	}
	
	//check username and password with database
	//@return bool
	public function checkMember($username, $password){

		$result = mysqli_query($this->con,"SELECT * FROM users");

		while($row = mysqli_fetch_array($result)){
			if($username == $row['Username'] && $password == $row['Password']){
				return TRUE;
			}
  		}
		return FALSE;
	}
	//edits comment in database		
	public function fixComment($editId, $newComment){

		$sql = "UPDATE comments SET comments=?
		WHERE UniqueId=?";
		$stmt = mysqli_prepare($this->con, $sql);
		mysqli_stmt_bind_param ($stmt, "ss",$newComment,$editId);
		mysqli_stmt_execute($stmt);
		mysqli_stmt_close($stmt);
		mysqli_close($this->con);
	}
	//deletes comments in database
	public function commentDelete($unique){
		$sql = "DELETE FROM comments WHERE UniqueId=?";
		$stmt = mysqli_prepare($this->con, $sql);
		mysqli_stmt_bind_param ($stmt, "s",$unique);
		mysqli_stmt_execute($stmt);
		mysqli_stmt_close($stmt);
		mysqli_close($this->con);
	}
	//deletes images comments in database
	public function ImgDelete($value){
		$sql = "DELETE FROM comments WHERE Id=?";
		$stmt = mysqli_prepare($this->con, $sql);
		mysqli_stmt_bind_param ($stmt, "s",$value);
		mysqli_stmt_execute($stmt);
		mysqli_stmt_close($stmt);
		mysqli_close($this->con);
	}
		//adds comment to database
	public function saveComments($pictureId, $user, $comments){
		$comments = strip_tags($comments);
		
		$sql = "INSERT INTO comments (Id, User, comments)
			VALUES (?,?,?)";
		$stmt = mysqli_prepare($this->con, $sql);
		mysqli_stmt_bind_param ($stmt, "sss",$pictureId, $user, $comments);
		mysqli_stmt_execute($stmt);
		mysqli_stmt_close($stmt);
		mysqli_close($this->con);
	}
}